package com.ruoyi.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.ruoyi.auth.form.*;
import com.ruoyi.auth.utils.SmsUtil;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController {
    //短信验证码
    private static Integer ercode;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    //redis
    @Autowired
    private RedisService redisService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    /**
     * 商家端登录接口
     */
    @PostMapping("businessLogin")
    public R<?> businessLogin(@RequestBody BusinessLoginBody form) {
        //判断验证码是否正确
        if (!redisService.hasKey("ercodeLogin:" + form.getMobile())) {
            throw new ServiceException("短信验证码过期！");
        }
        String code = Integer.toString(redisService.getCacheObject("ercodeLogin:" + form.getMobile()));
        String ercode = form.getCode();
        if (!ercode.equals(code)) {
            throw new ServiceException("短信验证码错误！");
        }
        // 商家登录
        LoginUser userInfo = sysLoginService.businessLogin(form.getMobile(), "123456");
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 商家端注册接口
     */
    @PostMapping("businessRegister")
    public R<?> businessRegister(@RequestBody BusinessRegisterBody businessRegisterBody) {
        // 用户注册
        System.out.println(businessRegisterBody);
        sysLoginService.businessRegister(businessRegisterBody);
        return R.ok("恭喜你注册成功！");
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("msg")
    public R<?> msg(@RequestBody SmsCode smsCode) {
        //手机号校验
        if (!Pattern.compile("^1[3-9]\\d{9}$").matcher(smsCode.getMobile()).matches()) {
            return R.fail("手机号格式不正确");
        }
        //随机生成4位数验证码
        ercode = new Random().nextInt(9000) + 1000;
        String key = null;
        System.out.println(ercode);
        if (smsCode.getResource()==0) {
            key = "ercodeLogin:" + smsCode.getMobile();
        } else if (smsCode.getResource()==1) {
            key = "ercodeRegister:" + smsCode.getMobile();
        }
        redisService.setCacheObject(key, ercode, 10L, TimeUnit.HOURS);
        // 用户注册
        SmsUtil.sendSms(smsCode.getMobile(), "阿里云短信测试", "SMS_154950909",
                JSON.toJSONString(new Code(ercode)));

        return R.ok();
    }

    /**
     * 用户端登录接口
     * @param form
     * @return
     */
    @PostMapping("userLogin")
    public R<?> userLogin(@RequestBody BusinessLoginBody form) {
        //判断验证码是否正确
        if (!redisService.hasKey("ercodeLogin:" + form.getMobile())) {
            throw new ServiceException("短信验证码过期！");
        }
        String code = Integer.toString(redisService.getCacheObject("ercodeLogin:" + form.getMobile()));
        String ercode = form.getCode();
        if (!ercode.equals(code)) {
            throw new ServiceException("短信验证码错误！");
        }
        // 用户登录
        LoginUser userInfo = sysLoginService.userLogin(form.getMobile(), "123456");
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

}
